<script setup lang="tsx">
import {
  ElLink,
  ElRow,
  ElCol,
  ElButton,
  ElUpload,
  ElTooltip,
  UploadProps,
  ElMessage
} from 'element-plus'
import {
  getImportTemplateApi,
  deleteImportDataApi,
  getTemplateFileApi
} from '@/api/dispatch/taskpool'
import { reactive, ref } from 'vue'
import { PATH_URL } from '@/axios/service'
import { useTable } from '@/hooks/web/useTable'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { Descriptions, DescriptionsSchema } from '@/components/Descriptions'
import { Search } from '@/components/Search'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getTemplateFileApi()
    return {
      list: res.data,
      total: res.count
    }
  }
})
const { loading, dataList } = tableState
const { getList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    type: 'expand',
    width: 80,
    fixed: true,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    slots: {
      default: (data: any) => {
        // const table1 = reactive<TableColumn[]>([
        //   {
        //     field: '序号',
        //     label: '序号'
        //   },
        //   {
        //     field: '型号',
        //     label: '型号'
        //   },
        //   {
        //     field: '工艺文件号',
        //     label: '工艺文件号'
        //   },
        //   {
        //     field: '工艺文件名',
        //     label: '工艺文件号'
        //   },
        //   {
        //     field: '架次',
        //     label: '架次'
        //   },
        //   {
        //     field: '工位',
        //     label: '工位'
        //   },
        //   {
        //     field: '二级工位',
        //     label: '二级工位'
        //   },
        //   {
        //     field: '站位',
        //     label: '站位'
        //   },
        //   {
        //     field: '工单号',
        //     label: '工单号'
        //   },
        //   {
        //     field: '工单状态',
        //     label: '工单状态'
        //   },
        //   {
        //     field: '工单类型',
        //     label: '工单类型'
        //   },
        //   {
        //     field: '所需资质',
        //     label: '所需资质'
        //   },
        //   {
        //     field: '所需人员',
        //     label: '所需人员'
        //   }
        // ])
        const detailSchema = reactive<DescriptionsSchema[]>([
          {
            field: '工单列表',
            label: '工单列表'
          },
          {
            field: '工单工序',
            label: '工单工序'
          },
          {
            field: '班组列表',
            label: '班组列表'
          },
          {
            field: '班组用户',
            label: '班组用户'
          },
          {
            field: '物流配送通知',
            label: '物流配送通知'
          },
          {
            field: '物流配送状态',
            label: '物流配送状态'
          },
          {
            field: '周计划列表',
            label: '周计划列表'
          },
          {
            field: '日计划列表',
            label: '日计划列表'
          }
        ])
        return (
          <>
            <Descriptions schema={detailSchema} data={data.row.detail} />
          </>
        )
      }
    }
  },
  {
    field: 'name',
    label: '文件名',
    fixed: true,
    search: {
      hidden: true
    }
  },
  {
    field: 'size',
    label: '大小',
    fixed: true,
    search: {
      hidden: true
    },
    slots: {
      default: (data: any) => {
        return <>{(data.row.size / 1024).toFixed(1) + 'KB'}</>
      }
    }
  },
  {
    field: 'ctime',
    label: '时间',
    fixed: true,
    search: {
      hidden: true
    },
    slots: {
      default: (data: any) => {
        return <>{data.row.ctime}</>
      }
    }
  },
  {
    field: 'action',
    label: '操作',
    minWidth: '60px',
    search: {
      hidden: true
    },
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElButton link size="small" type="primary" onClick={() => handleDelete(data.row)}>
              删除
            </ElButton>
          </>
        )
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const beforeFileUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const isExcel = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].includes(
    rawFile.type
  )
  const isLtSize = rawFile.size / 1024 / 1024 < 10

  if (!isExcel) {
    ElMessage.error('上传文件必须是 XLSX 格式!')
  }
  if (!isLtSize) {
    ElMessage.error('上传文件大小不能超过 10MB!')
  }
  return isExcel && isLtSize
}

const handleUpload = async (response) => {
  if (response.code === 200) {
    getList()
  } else {
    ElMessage.error(response.message)
  }
}

const handleDelete = async (row) => {
  const res = await deleteImportDataApi({ path: row.path })
  if (res) {
    getList()
  }
}

const downloadTemplate = async () => {
  ElMessage.info('正在下载请稍等！')
  const res = await getImportTemplateApi()
  if (res) {
    const a = document.createElement('a')
    a.style.display = 'none'
    a.href = PATH_URL + res.data.url
    console.log('a.href', a.href)
    a.target = '_blank'
    a.download = res.data.filename
    const event = new MouseEvent('click')
    a.dispatchEvent(event)
  }
}
</script>

<template>
  <div>
    <span>导入步骤：</span>
    <ol>
      <li style="margin-top: 7px">
        <ElLink @click="downloadTemplate" target="_blank" type="primary"> 下载导入模板 </ElLink>
      </li>
      <li style="margin-top: 7px">编辑模板文件（将需要导入的数据按格式填写进去）</li>
      <li style="margin-top: 7px">点击上传文件，上传编辑后的模板文件</li>
      <li style="margin-top: 7px">查看导入结果，检查相关表格行数是否正确</li>
    </ol>
  </div>
  <div>
    <!-- <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" /> -->
    <ElRow :gutter="10" class="!mt-0 !mr-0 mb-1">
      <ElCol :span="1.5">
        <div>
          <ElUpload
            :action="`${PATH_URL}/upload/file`"
            :data="{ path: 'dispatch/taskpool' }"
            :show-file-list="false"
            :before-upload="beforeFileUpload"
            :on-success="handleUpload"
            accept=".xlsx"
          >
            <ElTooltip effect="dark" content="只支持上传XLSX文件" placement="top">
              <ElButton type="primary">上传文件</ElButton>
            </ElTooltip>
          </ElUpload>
        </div>
      </ElCol>
    </ElRow>
    <Table
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :fit="true"
    />
  </div>
</template>
